package com.example.hlddz2.viewmodel;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.hlddz2.model.Category;
import com.example.hlddz2.repository.ProductRepository;

import java.util.Collections;
import java.util.List;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableObserver;

public class CategoryViewModel extends ViewModel {
    private final ProductRepository repository;
    private final CompositeDisposable disposable = new CompositeDisposable();

    private final MutableLiveData<List<Category>> topCategories = new MutableLiveData<>();
    private final MutableLiveData<List<Category>> subCategories = new MutableLiveData<>();
    private int selectedIndex = 0;

    public CategoryViewModel(ProductRepository repository) {
        this.repository = repository;
    }

    public LiveData<List<Category>> getTopCategories() {
        return topCategories;
    }

    public LiveData<List<Category>> getSubCategories() {
        return subCategories;
    }

    public void loadCategories() {
        disposable.add(repository.getCategories()
                .subscribeWith(new DisposableObserver<List<Category>>() {
                    @Override
                    public void onNext(List<Category> categories) {
                        topCategories.setValue(categories);
                        if (categories != null && !categories.isEmpty()) {
                            selectCategory(0);
                        } else {
                            subCategories.setValue(Collections.emptyList());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        topCategories.setValue(Collections.emptyList());
                        subCategories.setValue(Collections.emptyList());
                    }

                    @Override
                    public void onComplete() {}
                }));
    }

    public void selectCategory(int index) {
        selectedIndex = index;
        List<Category> categories = topCategories.getValue();
        if (categories != null && index >= 0 && index < categories.size()) {
            List<Category> children = categories.get(index).getChildren();
            subCategories.setValue(children == null ? Collections.emptyList() : children);
        }
    }

    public int getSelectedIndex() {
        return selectedIndex;
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        disposable.clear();
    }
}


